﻿using BasicInformation.ApiRead.Application.Command.Category;
using BasicInformation.ApiRead.Application.Command.Unit;
using BasicInformation.Domain;
using BasicInformation.Dtos;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Unit
{
    public class GetUnitHandler:IRequestHandler<GetUnitCommand,ApiPaging<UnitModel>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<GetUnitHandler> logger;

        public GetUnitHandler(DatabaseContext db, ILogger<GetUnitHandler> logger)
        {
            this.db = db;
            this.logger = logger;
        }

        public async Task<ApiPaging<UnitModel>> Handle(GetUnitCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<UnitModel> result = new ApiPaging<UnitModel>();
            StringBuilder sql = new StringBuilder();
            StringBuilder countSql = new StringBuilder();


            // 主查询SQL - 获取单位信息
            sql.Append(@"SELECT
                UnitId,
                UnitCode,
                UnitName,
                UnitRemark
            FROM
                unitmodel 
            WHERE
                IsDel = 0");  // 确保使用正确的表别名或直接使用字段名

            // 计数SQL - 必须包含相同条件
            countSql.Append(@"SELECT COUNT(*) 
                    FROM unitmodel
                    WHERE IsDel = 0");

            // 添加查询条件 - 单位编号精确查询
            if (!string.IsNullOrWhiteSpace(request.UnitCode))
            {
                sql.Append(" AND UnitCode = @UnitCode");  // 移除表别名'a.'，与主查询一致
                countSql.Append(" AND UnitCode = @UnitCode");
            }

            // 添加查询条件 - 单位名称模糊查询
            if (!string.IsNullOrWhiteSpace(request.UnitName))
            {
                sql.Append(" AND UnitName LIKE @UnitName");  // 移除表别名'a.'
                countSql.Append(" AND UnitName LIKE @UnitName");
            }

            // 添加排序和分页
            sql.Append(" ORDER BY UnitId DESC LIMIT @size OFFSET @offset");

            // 设置参数
            var parameters = new
            {
                UnitCode = request.UnitCode,
                UnitName = string.IsNullOrEmpty(request.UnitName) ? null : $"%{request.UnitName}%",
                offset = (request.index - 1) * request.size,
                size = request.size 
            };

            try
            {
                logger.LogDebug("执行单位查询: {sql}", sql.ToString());
                logger.LogDebug("查询参数: {@parameters}", parameters);
                var pageData = await db.DapperConnection.QueryAsync<UnitModel>(sql.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(countSql.ToString(), parameters);

                // 安全计算总页数
                int totalPage =  (int)Math.Ceiling(totalCount / (double)request.size) ;

                // 设置返回结果
                result.Msg = "单位查询成功";
                result.Code = ApiEnum.OK;
                result.Data = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPCount = totalPage;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "单位查询失败 - SQL: {sql}, 参数: {@parameters}", sql.ToString(), parameters);
                result.Code = ApiEnum.Fail;
                result.Msg = "单位查询失败";
            }

            return result;
        }
    }
}
